package com.geeguo.ebuilder.operation.controller.system.user;

import com.geeguo.ebuilder.core.common.action.ActionResult;
import com.geeguo.ebuilder.core.common.model.vo.PageListVO;
import com.geeguo.ebuilder.core.common.utils.key.UUIDCheckUtils;
import com.geeguo.ebuilder.core.common.utils.key.UUIDGenerator;
import com.geeguo.ebuilder.core.security.annotation.Logical;
import com.geeguo.ebuilder.core.security.annotation.RequiresLogin;
import com.geeguo.ebuilder.core.security.annotation.RequiresPermissions;
import com.geeguo.ebuilder.operation.base.core.constants.MessageConstants;
import com.geeguo.ebuilder.operation.base.security.model.LoginUser;
import com.geeguo.ebuilder.operation.base.security.utils.AuthUtils;
import com.geeguo.ebuilder.operation.business.system.role.service.RoleService;
import com.geeguo.ebuilder.operation.business.system.user.model.*;
import com.geeguo.ebuilder.operation.business.system.user.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@Tag(name = "用户信息")
@RestController
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;

    @Operation(summary = "分页查询列表")
    @PostMapping("/system/user/list")
    @RequiresPermissions("System:User:List")
    public ActionResult<PageListVO<UserVO>> list(@RequestBody UserQuery query) {
        PageListVO<UserVO> page = userService.list(query);
        return ActionResult.page(page);
    }

    @Operation(summary = "保存")
    @PostMapping("/system/user/save")
    @RequiresPermissions("System:User:Add")
    public ActionResult<Boolean> save(@Validated @RequestBody UserCreateDTO dto) {
        if (StringUtils.isNotBlank(dto.getUsername())) {
            if (userService.existsUsername(dto.getUsername())) {
                return ActionResult.fail("用户名已经存在");
            }
        }
        if (StringUtils.isNotBlank(dto.getMobile())) {
            if (userService.existsMobile(dto.getMobile())) {
                return ActionResult.fail("移动电话已经存在");
            }
        }
        if (StringUtils.isNotBlank(dto.getEmail())) {
            if (userService.existsMobile(dto.getEmail())) {
                return ActionResult.fail("电子邮件已经存在");
            }
        }
        LoginUser currentUser = AuthUtils.getLoginUser();
        UserEntity user = UserConverter.INSTANCE.convert2Entity(dto);
        user.setId(UUIDGenerator.getId());
        user.setCreateTime(new Date());
        user.setCreateUser(currentUser.getUserId());
        if (userService.save(user, dto.getRoles() )) {
            return ActionResult.success(true);
        }
        return ActionResult.fail();
    }

    @Operation(summary = "根据ID获取信息")
    @GetMapping("/system/user/get/{id}")
    @RequiresPermissions(value = {"System:User:Add", "System:User:Edit"}, logical = Logical.OR)
    public ActionResult<UserVO> get(@PathVariable("id") String id) {
        if (UUIDCheckUtils.check(id)) {
            UserEntity entity = userService.get(id);
            if (entity != null) {
                UserVO user = UserConverter.INSTANCE.convert2VO(entity);
                user.setRoles(roleService.listIdByUser(user.getId()));
                return ActionResult.success(user);
            }
            return ActionResult.fail(MessageConstants.FAIL_DATA_NOT_EXIST);
        }
        return ActionResult.fail(MessageConstants.FAIL_REQUEST_DATA_ERROR);
    }

    @Operation(summary = "更新")
    @PostMapping("/system/user/update")
    @RequiresPermissions("System:User:Edit")
    public ActionResult<Boolean> update(@Validated @RequestBody UserUpdateDTO dto) {
        LoginUser currentUser = AuthUtils.getLoginUser();
        UserEntity old = userService.get(dto.getId());
        if (old != null) {
            if (StringUtils.isNotBlank(dto.getUsername()) && !dto.getUsername().equals(old.getUsername())) {
                if (userService.existsUsername(dto.getUsername())) {
                    return ActionResult.fail("用户名已经存在");
                }
            }
            if (StringUtils.isNotBlank(dto.getMobile()) && !dto.getMobile().equals(old.getMobile())) {
                if (userService.existsMobile(dto.getMobile())) {
                    return ActionResult.fail("移动电话已经存在");
                }
            }
            if (StringUtils.isNotBlank(dto.getEmail()) && !dto.getEmail().equals(old.getEmail())) {
                if (userService.existsEmail(dto.getEmail())) {
                    return ActionResult.fail("电子邮件已经存在");
                }
            }
            UserEntity user = UserConverter.INSTANCE.convert2Entity(dto);
            user.setModifyTime(new Date());
            user.setModifyUser(currentUser.getUserId());
            if (userService.update(user, old, dto.getRoles())) {
                return ActionResult.success(true);
            }
        }
        return ActionResult.fail();
    }

    @Operation(summary = "删除")
    @PostMapping("/system/user/remove")
    @RequiresPermissions("System:User:Remove")
    public ActionResult<Boolean> remove(@RequestParam("id") String id) {
        if (UUIDCheckUtils.check(id)) {
            LoginUser currentUser = AuthUtils.getLoginUser();
            if (id.equals(currentUser.getUserId())) {
                return ActionResult.fail("不能删除自己");
            }
            if (userService.remove(id)) {
                return ActionResult.success(true);
            } else {
                return ActionResult.fail();
            }
        }
        return ActionResult.fail(MessageConstants.FAIL_REQUEST_DATA_ERROR);
    }

    @Operation(summary = "更新密码")
    @PostMapping("/system/user/updatePassword")
    @RequiresPermissions("System:User:EditPassword")
    public ActionResult<Boolean> updatePassword(@Validated @RequestBody UserUpdatePasswordDTO dto) {
        LoginUser currentUser = AuthUtils.getLoginUser();
        if (userService.updatePassword(dto.getId(), dto.getPassword(), new Date(), currentUser.getUserId())) {
            return ActionResult.success(true);
        }
        return ActionResult.fail();
    }

    @Operation(summary = "分页查询用户简单信息（有效），通用方法，登录即可访问")
    @PostMapping("/system/user/listSimple")
    @RequiresLogin
    public ActionResult<PageListVO<UserSimpleVO>> listSimple(@RequestBody UserQuery query) {
        return ActionResult.page(userService.listSimple(query));
    }

    @Operation(summary = "模糊查询用户简单信息（有效），必须要有搜索关键字，最多只返回50条，通用方法，登录即可访问")
    @PostMapping("/system/user/search")
    @RequiresLogin
    public ActionResult<List<UserSimpleVO>> search(@RequestParam String realName) {
        List<UserSimpleVO> userList = null;
        if (StringUtils.isNotEmpty(realName)) {
            userList = userService.search(realName);
        }
        return ActionResult.success(userList);
    }
}